<template>
  <div class="goods-image">
    <div class="middle" ref="target">
      <img :src="imgList[activeIndex]" alt="" />
      <div class="layer" v-show="!isOutside" :style="layerPos"></div>
    </div>
    <div class="large" v-show="!isOutside">
      <img :src="imgList[activeIndex]" alt="" :style="largePos" />
    </div>
    <ul class="small">
      <li v-for="(img, index) in imgList" :key="index" @mouseenter="activeIndex = index"
        :class="{ active: activeIndex === index }">
        <img :src="img" alt="" />
      </li>
    </ul>
  </div>
</template>

<script>
export default {
  name: 'GoodsImage'
}
</script>

<script setup>
import { reactive, ref, watch } from 'vue'
import { useMouseInElement } from '@vueuse/core'
defineProps({
  imgList: {
    type: Array,
    default: () => []
  }
})

const activeIndex = ref(0)
const target = ref(null)
const layerPos = reactive({ top: 0, left: 0 })
const largePos = reactive({ top: 0, left: 0 })
const { elementX, elementY, isOutside } = useMouseInElement(target)

watch([elementX, elementY], () => {
  let top = elementY.value - 100
  let left = elementX.value - 100

  if (top < 0) top = 0
  if (left < 0) left = 0
  if (top > 200) top = 200
  if (left > 200) left = 200

  layerPos.top = `${top}px`
  layerPos.left = `${left}px`

  largePos.top = `${-1 * 2 * top}px`
  largePos.left = `${-1 * 2 * left}px`
})
</script>

<style scoped lang="less">
.goods-image {
  width: 480px;
  height: 400px;
  position: relative;
  display: flex;

  .middle {
    width: 400px;
    height: 400px;
    background: #f5f5f5;
    position: relative;
    cursor: move;

    .layer {
      width: 200px;
      height: 200px;
      background: rgba(0, 0, 0, .2);
      left: 0;
      top: 0;
      position: absolute;
    }
  }

  .large {
    position: absolute;
    top: 0;
    left: 412px;
    width: 400px;
    height: 400px;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
    background-repeat: no-repeat;
    background-size: 800px 800px;
    background-color: #f8f8f8;
    overflow: hidden;
    z-index: 401;

    img {
      max-width: 800px;
      max-height: 800px;
      width: 800px;
      height: 800px;
      position: absolute;
      left: 0;
      top: 0;
    }
  }

  .small {
    width: 80px;

    li {
      width: 68px;
      height: 68px;
      margin-left: 12px;
      margin-bottom: 15px;
      cursor: pointer;

      &:hover,
      &.active {
        border: 2px solid @xtxColor;
      }
    }
  }
}
</style>